import { observable, action } from "mobx";
import _action from "../apis/app";
import { displayTypes, fillinTypes } from "../constants/app";

export default class AppFormStore {
  @observable fillinTypes = null;
  @observable displayTypes = null;

  @action init = () => {
    return Promise.all([
      this.getDisplayTypes(),
      this.getFillinTypes()
    ]);
  }

  @action initForm = (form, fields) => {
    this.init().then(() => {
      this.initFormOpts(form, fields);
    });
  }

  @action updateForm = (form, fields) => {
    this.updateFormOpts(form, fields);
  }

  initFormOpts(form, { displayType, fillinType }) {
    const dtOpts = this.displayTypes.map(dt => this.map(dt, displayType));
    const ftOpts = this.fillinTypes.map(ft => this.map(ft, fillinType, displayType));
    form.setField("displayType", { options: dtOpts });
    form.setField("fillinType", { options: ftOpts });
    form.updateFields({
      displayType: { value: displayType || displayTypes.EXCEL },
      fillinType: { value: fillinType || fillinTypes.MULTI }
    });
  }

  updateFormOpts = (form, { displayType, fillinType }) => {
    const { fillinTypes, map } = this;
    const ftOpts = fillinTypes.map(ft => map(ft, fillinType, displayType));
    form.setField("fillinType", { options: ftOpts });
  }

  getDisplayTypes() {
    return new Promise(resolve => {
      if (!this.displayTypes) {
        return _action.getDisplayTypes().then(types => {
          this.displayTypes = types;
          resolve(types);
        });
      }

      resolve(this.displayTypes);
    });
  }

  getFillinTypes() {
    return new Promise(resolve => {
      if (!this.fillinTypes) {
        return _action.getFillinTypes().then(types => {
          this.fillinTypes = types;
          resolve(types);
        });
      }

      resolve(this.fillinTypes);
    });
  }

  map({ name, face }, key = fillinTypes.MULTI, displayType = displayTypes.EXCEL) {
    return {
      key: name,
      showname: face,
      selected: name === key,
      disabled: (displayType === displayTypes.FORM && name === fillinTypes.MULTI) || (displayType === displayTypes.EXCEL && name === fillinTypes.FREE)
    };
  }
}